package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.dto.ProjectOptionDTO;
import com.tju.ocean_ecology_website.dto.ServiceHourRejectDTO;
import com.tju.ocean_ecology_website.dto.ServiceHoursQueryDTO;
import com.tju.ocean_ecology_website.entity.Activity;
import com.tju.ocean_ecology_website.entity.VolunteerInfo;
import com.tju.ocean_ecology_website.entity.VolunteerServiceRecord;
import com.tju.ocean_ecology_website.service.ActivityService;
import com.tju.ocean_ecology_website.service.VolunteerInfoService;
import com.tju.ocean_ecology_website.service.VolunteerServiceRecordService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务时长管理控制器
 */
@RestController
@RequestMapping("/api")
public class ServiceHoursController {

    @Autowired
    private VolunteerServiceRecordService volunteerServiceRecordService;

    @Autowired
    private VolunteerInfoService volunteerInfoService;

    @Autowired
    private ActivityService activityService;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 获取服务时长记录列表
     *
     * @param queryDTO 查询参数
     * @return 服务时长记录列表
     */
    @GetMapping("/service-hours")
    public ResponseEntity<ApiResponse<PageResult<VolunteerServiceRecord>>> getServiceHoursList(ServiceHoursQueryDTO queryDTO) {
        // 创建服务时长记录筛选条件
        VolunteerServiceRecord recordQuery = new VolunteerServiceRecord();

        // 如果有志愿者姓名，需要先查询志愿者ID
        if (queryDTO.getVolunteerName() != null && !queryDTO.getVolunteerName().isEmpty()) {
            // 这里简化处理，实际应该通过志愿者姓名查询志愿者ID
            // 由于当前系统没有直接通过姓名查询志愿者的方法，这里只是示例
            VolunteerInfo volunteerInfo = new VolunteerInfo();
            volunteerInfo.setRealName(queryDTO.getVolunteerName());
            Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(volunteerInfo, PageRequest.of(0, 1));
            if (!volunteerInfoPage.isEmpty()) {
                recordQuery.setVolunteerId(volunteerInfoPage.getContent().get(0).getId());
            } else {
                // 如果没有找到匹配的志愿者，返回空结果
                return ResponseEntity.ok(ApiResponse.success(new PageResult<>(new ArrayList<>(), 0, queryDTO.getPage(), queryDTO.getPageSize(), 0)));
            }
        }

        if (queryDTO.getActivityId() != null) {
            recordQuery.setActivityId(queryDTO.getActivityId());
        }

        if (queryDTO.getStatus() != null) {
            if ("verified".equals(queryDTO.getStatus())) {
                recordQuery.setStatus(1); // 已认证
            } else if ("pending".equals(queryDTO.getStatus())) {
                recordQuery.setStatus(0); // 待认证
            } else if ("rejected".equals(queryDTO.getStatus())) {
                recordQuery.setStatus(2); // 已拒绝
            }
        }

        // 处理日期范围查询
        try {
            if (queryDTO.getStartDate() != null && !queryDTO.getStartDate().isEmpty()) {
                Date startDate = dateFormat.parse(queryDTO.getStartDate());
                // 这里简化处理，实际应该在DAO层添加日期范围查询
                recordQuery.setServiceDate(startDate);
            }

            if (queryDTO.getEndDate() != null && !queryDTO.getEndDate().isEmpty()) {
                // 结束日期在DAO层处理
                // 这里简化处理，实际应该在DAO层添加日期范围查询
            }
        } catch (ParseException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "日期格式错误"));
        }

        // 查询服务时长记录
        PageRequest pageRequest = queryDTO.toPageRequest();
        Page<VolunteerServiceRecord> recordPage = volunteerServiceRecordService.queryByPage(recordQuery, pageRequest);

        // 创建分页结果
        PageResult<VolunteerServiceRecord> pageResult = PageResult.fromPage(recordPage, queryDTO.getPage());

        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取服务时长记录详情
     *
     * @param id 记录ID
     * @return 记录详情
     */
    @GetMapping("/service-hours/{id}")
    public ResponseEntity<ApiResponse<VolunteerServiceRecord>> getServiceHourDetail(@PathVariable("id") Long id) {
        VolunteerServiceRecord record = volunteerServiceRecordService.queryById(id);
        if (record == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "服务时长记录不存在"));
        }

        return ResponseEntity.ok(ApiResponse.success(record));
    }

    /**
     * 审核通过时长记录
     *
     * @param id 记录ID
     * @return 审核结果
     */
    @PostMapping("/service-hours/{id}/approve")
    public ResponseEntity<ApiResponse<VolunteerServiceRecord>> approveServiceHour(@PathVariable("id") Long id) {
        VolunteerServiceRecord record = volunteerServiceRecordService.approveServiceHour(id);
        if (record == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "服务时长记录不存在"));
        }

        return ResponseEntity.ok(ApiResponse.success(record, "审核通过成功"));
    }

    /**
     * 拒绝时长记录
     *
     * @param id 记录ID
     * @param rejectDTO 拒绝信息
     * @return 拒绝结果
     */
    @PostMapping("/service-hours/{id}/reject")
    public ResponseEntity<ApiResponse<VolunteerServiceRecord>> rejectServiceHour(
            @PathVariable("id") Long id,
            @Valid @RequestBody ServiceHourRejectDTO rejectDTO) {

        VolunteerServiceRecord record = volunteerServiceRecordService.rejectServiceHour(id, rejectDTO.getReason());
        if (record == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "服务时长记录不存在"));
        }

        return ResponseEntity.ok(ApiResponse.success(record, "拒绝服务时长成功"));
    }

    /**
     * 导出服务时长记录
     *
     * @param queryDTO 查询参数
     * @return Excel文件
     */
    @GetMapping("/service-hours/export")
    public ResponseEntity<byte[]> exportServiceHours(ServiceHoursQueryDTO queryDTO) {
        // 创建服务时长记录筛选条件
        VolunteerServiceRecord recordQuery = new VolunteerServiceRecord();

        // 如果有志愿者姓名，需要先查询志愿者ID
        if (queryDTO.getVolunteerName() != null && !queryDTO.getVolunteerName().isEmpty()) {
            // 这里简化处理，实际应该通过志愿者姓名查询志愿者ID
            VolunteerInfo volunteerInfo = new VolunteerInfo();
            volunteerInfo.setRealName(queryDTO.getVolunteerName());
            Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(volunteerInfo, PageRequest.of(0, 1));
            if (!volunteerInfoPage.isEmpty()) {
                recordQuery.setVolunteerId(volunteerInfoPage.getContent().get(0).getId());
            }
        }

        if (queryDTO.getActivityId() != null) {
            recordQuery.setActivityId(queryDTO.getActivityId());
        }

        if (queryDTO.getStatus() != null) {
            if ("verified".equals(queryDTO.getStatus())) {
                recordQuery.setStatus(1); // 已认证
            } else if ("pending".equals(queryDTO.getStatus())) {
                recordQuery.setStatus(0); // 待认证
            } else if ("rejected".equals(queryDTO.getStatus())) {
                recordQuery.setStatus(2); // 已拒绝
            }
        }

        // 查询服务时长记录
        List<VolunteerServiceRecord> records = volunteerServiceRecordService.exportServiceHours(recordQuery);

        // 创建Excel文件
        try {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("服务时长记录");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"志愿者姓名", "活动名称", "服务时长(小时)", "服务日期", "服务地点", "服务描述", "状态"};

            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            // 填充标题
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.autoSizeColumn(i);
            }

            // 填充数据
            int rowNum = 1;
            for (VolunteerServiceRecord record : records) {
                Row row = sheet.createRow(rowNum++);

                row.createCell(0).setCellValue(record.getVolunteerName() != null ? record.getVolunteerName() : "");
                row.createCell(1).setCellValue(record.getActivityTitle() != null ? record.getActivityTitle() : "");
                row.createCell(2).setCellValue(record.getServiceHours() != null ? record.getServiceHours() : 0);  // 这里是数字类型，不需要转换
                row.createCell(3).setCellValue(record.getServiceDate() != null ? dateFormat.format(record.getServiceDate()) : "");
                row.createCell(4).setCellValue(record.getServiceLocation() != null ? record.getServiceLocation() : "");
                row.createCell(5).setCellValue(record.getDescription() != null ? record.getDescription() : "");

                String status = "";
                if (record.getStatus() != null) {
                    switch (record.getStatus()) {
                        case 0:
                            status = "待审核";
                            break;
                        case 1:
                            status = "已通过";
                            break;
                        case 2:
                            status = "已拒绝";
                            break;
                        default:
                            status = "未知";
                    }
                }
                row.createCell(6).setCellValue(status);
            }

            // 调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 将工作簿写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();

            // 设置响应头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            httpHeaders.setContentDispositionFormData("attachment", "service_hours.xlsx");

            return ResponseEntity.ok()
                    .headers(httpHeaders)
                    .body(outputStream.toByteArray());

        } catch (IOException e) {
            return ResponseEntity.badRequest().body(new byte[0]);
        }
    }

    /**
     * 获取项目列表(下拉选择用)
     *
     * @return 项目选项列表
     */
    @GetMapping("/projects/options")
    public ResponseEntity<ApiResponse<List<ProjectOptionDTO>>> getProjectOptions() {
        List<Activity> activities = activityService.queryProjectOptions();

        List<ProjectOptionDTO> options = activities.stream()
                .map(activity -> ProjectOptionDTO.fromActivity(activity.getId(), activity.getTitle()))
                .collect(Collectors.toList());

        return ResponseEntity.ok(ApiResponse.success(options));
    }
}
